import React, { useState, useEffect } from 'react';
import { Table, Button, Upload, Modal, Form, Input, Select, Space, message, Popconfirm, Typography, Tag } from 'antd';
import { UploadOutlined, FileOutlined, DeleteOutlined, DownloadOutlined, PlusOutlined } from '@ant-design/icons';
import api from '../../services/api';

const { Option } = Select;
const { Title, Text } = Typography;

const PresetFileManagement = () => {
  const [files, setFiles] = useState([]);
  const [loading, setLoading] = useState(false);
  const [uploadModalVisible, setUploadModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [fileList, setFileList] = useState([]);
  const [uploading, setUploading] = useState(false);

  useEffect(() => {
    fetchFiles();
  }, []);

  const fetchFiles = async () => {
    setLoading(true);
    try {
      const response = await api.get('/admin/preset-files');
      setFiles(response.data);
    } catch (error) {
      message.error('获取预设文件列表失败');
      console.error('获取预设文件列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const showUploadModal = () => {
    form.resetFields();
    setFileList([]);
    setUploadModalVisible(true);
  };

  const handleCancel = () => {
    setUploadModalVisible(false);
  };

  const handleDelete = async (id) => {
    try {
      await api.delete(`/admin/preset-files/${id}`);
      message.success('文件删除成功');
      fetchFiles();
    } catch (error) {
      message.error('删除文件失败');
      console.error('删除文件失败:', error);
    }
  };

  const downloadFile = async (id, filename) => {
    try {
      const response = await api.get(`/admin/preset-files/${id}/download`, {
        responseType: 'blob'
      });
      
      // 创建下载链接
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', filename);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } catch (error) {
      message.error('下载文件失败');
      console.error('下载文件失败:', error);
    }
  };

  const uploadProps = {
    onRemove: file => {
      const index = fileList.indexOf(file);
      const newFileList = fileList.slice();
      newFileList.splice(index, 1);
      setFileList(newFileList);
    },
    beforeUpload: file => {
      setFileList([file]);
      return false;
    },
    fileList,
  };

  const handleUpload = async () => {
    try {
      const values = await form.validateFields();
      
      if (fileList.length === 0) {
        message.error('请选择要上传的文件');
        return;
      }
      
      const formData = new FormData();
      formData.append('file', fileList[0]);
      formData.append('name', values.name);
      formData.append('category', values.category);
      formData.append('description', values.description || '');
      
      setUploading(true);
      
      try {
        // 使用自定义配置，确保文件上传正确处理
        await api.post('/admin/preset-files', formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        });
        message.success('文件上传成功');
        setUploadModalVisible(false);
        fetchFiles();
      } catch (error) {
        message.error('上传文件失败: ' + (error.response?.data?.message || error.message));
        console.error('上传文件失败:', error);
      } finally {
        setUploading(false);
      }
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  const getFileTypeTag = (fileType) => {
    const typeColors = {
      'image': 'green',
      'document': 'blue',
      'video': 'purple',
      'audio': 'orange',
      'other': 'default'
    };
    
    const fileTypeDisplay = {
      'image': '图片',
      'document': '文档',
      'video': '视频',
      'audio': '音频',
      'other': '其他'
    };
    
    return (
      <Tag color={typeColors[fileType] || 'default'}>
        {fileTypeDisplay[fileType] || fileType}
      </Tag>
    );
  };

  const columns = [
    {
      title: '文件名',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <Space>
          <FileOutlined />
          <Text>{text}</Text>
        </Space>
      ),
    },
    {
      title: '原始文件名',
      dataIndex: 'originalFilename',
      key: 'originalFilename',
    },
    {
      title: '文件类型',
      dataIndex: 'fileType',
      key: 'fileType',
      render: (fileType) => getFileTypeTag(fileType),
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '大小',
      dataIndex: 'fileSize',
      key: 'fileSize',
      render: (size) => `${(size / 1024).toFixed(2)} KB`,
    },
    {
      title: '上传时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date) => new Date(date).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="primary" 
            icon={<DownloadOutlined />} 
            size="small"
            onClick={() => downloadFile(record.id, record.originalFilename)}
          >
            下载
          </Button>
          <Popconfirm
            title="确定要删除此文件吗?"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button 
              type="primary" 
              danger 
              icon={<DeleteOutlined />} 
              size="small"
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div className="preset-file-management-container">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
        <Title level={4}>预设文件管理</Title>
        <Button 
          type="primary" 
          icon={<PlusOutlined />} 
          onClick={showUploadModal}
        >
          上传新文件
        </Button>
      </div>

      <Table 
        columns={columns} 
        dataSource={files} 
        rowKey="id" 
        loading={loading}
        pagination={{ pageSize: 10 }}
      />

      <Modal
        title="上传预设文件"
        open={uploadModalVisible}
        onCancel={handleCancel}
        destroyOnHidden
        footer={[
          <Button key="back" onClick={handleCancel}>
            取消
          </Button>,
          <Button
            key="submit"
            type="primary"
            loading={uploading}
            onClick={handleUpload}
          >
            上传
          </Button>,
        ]}
      >
        <Form
          form={form}
          layout="vertical"
          name="uploadForm"
        >
          <Form.Item
            name="name"
            label="文件名称"
            rules={[{ required: true, message: '请输入文件名称' }]}
          >
            <Input placeholder="文件在系统中的显示名称" />
          </Form.Item>
          
          <Form.Item
            name="category"
            label="分类"
            rules={[{ required: true, message: '请选择文件分类' }]}
          >
            <Select placeholder="选择文件分类">
              <Option value="价格表">价格表</Option>
              <Option value="产品手册">产品手册</Option>
              <Option value="公司介绍">公司介绍</Option>
              <Option value="合同模板">合同模板</Option>
              <Option value="其他">其他</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="description"
            label="描述"
          >
            <Input.TextArea placeholder="文件描述（可选）" rows={3} />
          </Form.Item>
          
          <Form.Item
            label="文件"
            required
          >
            <Upload {...uploadProps}>
              <Button icon={<UploadOutlined />}>选择文件</Button>
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default PresetFileManagement; 